package org.example.projecttwo.service.Impl.news;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.projecttwo.entity.news.News;
import org.example.projecttwo.entity.dto.content.response.NewsDetailVO;
import org.example.projecttwo.mapper.news.NewsMapper;
import org.example.projecttwo.service.Inews.INewsService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 新闻基础信息表 服务实现类
 * </p>
 *
 * @author nn
 * @since 2025-11-01
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {

    @Override
    public IPage<News> pageByCondition(Page<News> page, Integer status, String keyword,
                                       String startTime, String endTime) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();

        // 状态筛选
        if (status != null) {
            queryWrapper.eq(News::getStatus, status);
        }

        // 关键词搜索（标题/内容）
        if (StringUtils.hasText(keyword)) {
            queryWrapper.and(wrapper -> wrapper
                    .like(News::getTitle, keyword)
                    .or()
                    .like(News::getContent, keyword));
        }

        // 时间范围筛选
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        if (StringUtils.hasText(startTime)) {
            queryWrapper.ge(News::getCreateTime, LocalDateTime.parse(startTime, formatter));
        }
        if (StringUtils.hasText(endTime)) {
            queryWrapper.le(News::getCreateTime, LocalDateTime.parse(endTime, formatter));
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(News::getCreateTime);

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public NewsDetailVO getNewsDetail(Long id) {
        News news = baseMapper.selectById(id);
        if (news == null) {
            return null;
        }
        NewsDetailVO detailVO = new NewsDetailVO();
        BeanUtils.copyProperties(news, detailVO);

        detailVO.setStatusName(getStatusName(news.getStatus()));
        detailVO.setRejectReason(news.getRejectReason());

        Map<String, Integer> statistics = baseMapper.getNewsStatistics(id);
        if (statistics == null) {
            statistics = new HashMap<>();
            statistics.put("viewCount", 0);
            statistics.put("likeCount", 0);
            statistics.put("collectCount", 0);
            statistics.put("commentCount", 0);
            statistics.put("reportedCount", 0);
        }
        detailVO.setStatistics(statistics);

        return detailVO;
    }

    @Override
    public void deleteNews(Long id, Integer deleteReason, String deleteRemark) {
        News news = baseMapper.selectById(id);
        if (news != null) {
            news.setStatus(5); // 5表示已删除状态
            news.setDeleteReason(deleteReason); // 保存删除原因
            news.setDeleteRemark(deleteRemark); // 保存删除备注
            news.setDeleteTime(LocalDateTime.now()); // 记录删除时间
            baseMapper.updateById(news);
        }
    }

    @Override
    public void submitAudit(Long id, Integer publishStrategy, String customPublishTime) {
        News news = baseMapper.selectById(id);
        if (news != null) {
            news.setStatus(1); // 1=待审核
            // 处理发布策略和定时发布时间（实际项目中需添加对应字段）
            baseMapper.updateById(news);
        }
    }

    @Override
    public void cancelAudit(Long id) {
        News news = baseMapper.selectById(id);
        if (news != null) {
            news.setStatus(0); // 0=草稿
            baseMapper.updateById(news);
        }
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        News news = new News();
        news.setId(id);
        news.setStatus(status);
        // 审核通过(已发布)时设置发布时间为当前时间
        if (status == 2) {
            news.setPublishTime(LocalDateTime.now()); // 设置当前发布时间
            news.setUpdateTime(LocalDateTime.now()); // 同时更新最后修改时间
        }
        baseMapper.updateById(news);
    }

    @Override
    public void unpublishNews(Long id, Integer offShelfReason) {
        News news = baseMapper.selectById(id);
        if (news != null) {
            news.setStatus(4); // 4=已下架
            news.setOffShelfReason(offShelfReason); // 保存下架原因
            news.setOffShelfTime(LocalDateTime.now()); // 记录下架时间
            baseMapper.updateById(news);
        }
    }

    @Override
    public void batchUpdateStatus(List<Long> ids, Integer status) {
        ids.forEach(id -> updateStatus(id, status));
    }

    @Override
    public void batchUnpublish(List<Long> ids, Integer offShelfReason) {
        ids.forEach(id -> unpublishNews(id, offShelfReason));
    }

    @Override
    public void batchDelete(List<Long> ids, Integer deleteReason, String deleteRemark) {
        ids.forEach(id -> deleteNews(id, deleteReason, deleteRemark));
    }

    @Override
    public int countPublishedNews() {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(News::getStatus, 2); // 2=审核通过（已发布）
        return Math.toIntExact(baseMapper.selectCount(queryWrapper));
    }

    @Override
    public void auditNews(Long id, Integer auditResult, String rejectReason) {
        News news = baseMapper.selectById(id);
        if (news != null) {
            // 获取当前登录的审核人用户名
            String auditUser = SecurityContextHolder.getContext().getAuthentication().getName();

            news.setStatus(auditResult);
            news.setAuditUser(auditUser);
            news.setAuditEndTime(LocalDateTime.now());

            // 审核未通过时设置拒绝原因，通过时清空
            if (auditResult == 3) {
                news.setRejectReason(rejectReason);
            } else {
                news.setRejectReason(null);
            }

            // 审核通过时设置发布时间
            if (auditResult == 2) {
                news.setPublishTime(LocalDateTime.now());
            }

            baseMapper.updateById(news);
        }
    }

    @Override
    public void batchAudit(List<Long> ids, Integer auditResult, String rejectReason) {
        String auditUser = SecurityContextHolder.getContext().getAuthentication().getName();
        LocalDateTime auditTime = LocalDateTime.now();

        ids.forEach(id -> {
            News news = baseMapper.selectById(id);
            if (news != null) {
                news.setStatus(auditResult);
                news.setAuditUser(auditUser);
                news.setAuditEndTime(auditTime);

                if (auditResult == 3) {
                    news.setRejectReason(rejectReason);
                } else {
                    news.setRejectReason(null);
                    if (auditResult == 2) {
                        news.setPublishTime(auditTime);
                    }
                }

                baseMapper.updateById(news);
            }
        });
    }

    @Override
    public Map<String, Integer> getNewsStatistics(Long id) {
        Map<String, Integer> stats = baseMapper.getNewsStatistics(id);
        if (stats == null) {
            stats = new HashMap<>();
            stats.put("viewCount", 0);
            stats.put("likeCount", 0);
            stats.put("collectCount", 0);
            stats.put("commentCount", 0);
            stats.put("reportedCount", 0);
        }
        return stats;
    }

    @Override
    public void increaseViewCount(Long id) {
        // 实际应使用乐观锁更新浏览量字段
        baseMapper.increaseViewCount(id);
    }

    // 在NewsServiceImpl的getUserDraftsByUserId方法中
    @Override
    public List<News> getUserDraftsByUserId(Long userId) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(News::getAuthorId, userId)
                .eq(News::getStatus, 0) // 草稿状态
                .orderByDesc(News::getUpdateTime);

        List<News> drafts = baseMapper.selectList(queryWrapper);

        // 处理publishTime为null的情况
        drafts.forEach(draft -> {
            if (draft.getPublishTime() == null) {
                // 可以设置为默认时间或空字符串（根据前端需求）
                draft.setPublishTime(LocalDateTime.MIN); // 示例：设置为最小时间
            }
        });

        return drafts;
    }

    @Override
    public void deleteDraft(Long id) {
        // 实际项目中应验证草稿属于当前用户
        baseMapper.deleteById(id);
    }

    @Override
    public IPage<News> pageByAuthor(Page<News> page, Long userId) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(News::getAuthorId, userId)
                .orderByDesc(News::getCreateTime);

        IPage<News> resultPage = baseMapper.selectPage(page, queryWrapper);

        // 处理publishTime为null的情况
        resultPage.getRecords().forEach(news -> {
            if (news.getPublishTime() == null) {
                // 未发布状态的新闻设置默认时间（如创建时间或最小时间）
                news.setPublishTime(news.getCreateTime() != null ?
                        news.getCreateTime() : LocalDateTime.MIN);
            }
        });

        return resultPage;
    }

    @Override
    public IPage<News> pageDeletedNews(Page<News> page, String keyword) {
        LambdaQueryWrapper<News> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(News::getStatus, 5); // 5=已删除

        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(News::getTitle, keyword);
        }

        queryWrapper.orderByDesc(News::getUpdateTime);
        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    public void restoreDeletedNews(List<Long> ids) {
        // 恢复为草稿状态
        ids.forEach(id -> {
            News news = new News();
            news.setId(id);
            news.setStatus(0); // 0=草稿
            baseMapper.updateById(news);
        });
    }

    @Override
    @Transactional
    public void permanentlyDeleteNews(List<Long> ids) {
        baseMapper.deleteBatchIds(ids);
    }

    /**
     * 获取状态名称
     */
    private String getStatusName(Integer status) {
        switch (status) {
            case 0: return "草稿";
            case 1: return "待审核";
            case 2: return "已发布";
            case 3: return "审核未通过";
            case 4: return "已下架";
            case 5: return "已删除";
            default: return "未知状态";
        }
    }


}